package mark;

import android.app.Activity;
import android.os.Build;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.FrameLayout;

/**
 * 创建时间：2018年02月08日15:31 <br>
 * 作者：fuchaoyang <br>
 * 描述：点击某个地方remove
 */

public class StickyMark {
  Activity mActivity;
  // attachview 有可能是ListView里的
  int[] location = new int[2];
  View mMarkView;
  private boolean hasStatusBar;
  FrameLayout.LayoutParams mLayoutParams;
  private final FrameLayout mContentLayout;

  public StickyMark(Activity activity) {
    mActivity = activity;
    hasStatusBar =
      (activity.getWindow().getAttributes().flags & WindowManager.LayoutParams.FLAG_FULLSCREEN)
        != WindowManager.LayoutParams.FLAG_FULLSCREEN
        && (activity.getWindow().getAttributes().flags
        & WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
        != WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;

    mContentLayout = (FrameLayout) activity.findViewById(android.R.id.content);
    mLayoutParams = new FrameLayout.LayoutParams(-2, -2);
  }

  public void setMarkView(View markView) {
    mMarkView = markView;
    mMarkView.setLayoutParams(mLayoutParams);
  }

  public void remove() {
    if (mMarkView.getParent() != null) {
      mContentLayout.removeView(mMarkView);
    }
  }

  public void attach(final View view) {
    /*((View) view.getParent()).getViewTreeObserver()
      .addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
        // 这个回调不及时？
        @Override public void onScrollChanged() {
          if (view.getWidth() != 0) {
            System.out.println("onScrollChanged = ");
            postAttach(view);
          }
        }
      });*/

    if (view.getWidth() == 0) {
      view.getViewTreeObserver()
        .addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
          @Override public void onGlobalLayout() {
            System.out.println("onGlobalLayout....");
            postAttach(view);
            if (Build.VERSION.SDK_INT >= 16) {
              view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            } else {
              view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            }
          }
        });
    } else {
      postAttach(view);
    }
  }

  // 右上角对其需要计算牟点和mark的宽高
  private void postAttach(final View view) {
    if (mMarkView.getParent() == null) mContentLayout.addView(mMarkView);
    // 这里能否监听的到view被移除
    //view.getLocationOnScreen(location);
    view.getLocationInWindow(location);
    System.out.println("location = " + location[0] + "," + location[1]);
    mLayoutParams.leftMargin = view.getWidth() / 2;
    mLayoutParams.topMargin =
      location[1] - (hasStatusBar ? ImmersiveUtil.getStatusBarHeightIfNeeded() : 0);
    //mMarkView.requestLayout();
    mMarkView.setLayoutParams(mLayoutParams);
  }
}
